import React, { Fragment, RefObject, FC, useEffect, useState, useMemo, useRef } from 'react'

import { type DetailResult } from "@/pages/types/type";
import { urlPrefix, getRequestInit } from '@/utils/http';
import { DotLoading, List, Grid, Space, Divider, Switch } from 'antd-mobile'
import dayjs from 'dayjs';
import { DATE_FOMRAT, DATE_TIME_FORMAT } from '@/constants';
import { UpdateDatePopup, UpdateNamePopup } from '../update';
import { type StaffLiving } from '@/pages/types/type';
import { DemoBlock } from '../demos-util';
import { DeleteButton } from '../delete';

const StaffLivings: FC<{ url: string, origin: number, includeDescendants: boolean, sp?: (x: StaffLiving) => any }> = ({ url, origin, includeDescendants, sp }) => {

    const [loadFails, setLoadFails] = useState<string[]>([]);
    const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
    const [loadingTimes, setLoadingTimes] = useState<number>(3);
    const [livings, setLivings] = useState<StaffLiving[]>([]);
    const [editing, setEditing] = useState<boolean>(false);

    function load() {
        let times = 1;
        const mznmf = `/api/${url}/${includeDescendants ? 'get-livings-by-origin-and-descendants' : 'get-livings-by-origin'}/${origin}`;
        let mznmfResponse: Promise<Response> = fetch(`${urlPrefix}${mznmf}`, getRequestInit())
        mznmfResponse.then(async (rsp: Response) => {
            if (rsp.ok) {
                await rsp.json().then(async ({ data, code, msg }: DetailResult<StaffLiving[]>) => {
                    if (code === 0) {
                        setLoadOK(msg);
                        setLivings(data!);
                    } else {
                        setLoadFails([...loadFails, msg]);
                    }
                }).catch(reason => {
                    setLoadFails([...loadFails, reason]);
                }).finally(() => {
                    console.log(`${mznmf} inner finally!`)
                })
            }
        }).catch((reason: any) => {
            console.error(reason);
            setLoadFails([...loadFails, `请求${mznmf}时发生错误：${reason}`])
        }).finally(() => {
            console.log(`${mznmf} outter finally!`)
            setLoadingTimes(--times);
        })
    }

    useEffect(load, [origin, url]);

    if (loadingTimes > 0) {
        return <div style={{ color: '#00b578' }}>
            <DotLoading color='currentColor' />
            <span>正在载入{loadingTimes}次...</span>
        </div>;
    }

    return <DemoBlock title={<><span> 参与员工({livings.length})</span> <Divider direction={'vertical'} />
        <Switch onChange={(checked: boolean) => {
            setEditing(checked);
        }} uncheckedText='编辑/删除' checkedText='编辑/删除' />
    </>} padding={8}>
        {!editing && <p>
            <Divider direction={'horizontal'} />
            {livings.map(({ leader, type, start, createdAt, remark, creator, id }) => {
                return <React.Fragment key={id}>{leader.name}{type.label.indexOf('参与') >= 0 ? '' : `(${type.label})`}
                <Divider direction={'vertical'} />
                </React.Fragment>
            })}
        </p>}
        {editing &&
            <List>
                {livings.map((living) => {
                    const { leader, type, start, createdAt, remark, creator, id } = living;
                    return <List.Item key={id}
                        description={<>
                            <Grid columns={1} gap={8} style={{ marginTop: "5px" }}>
                                <Grid.Item span={1}>
                                    <Space wrap>
                                        生效时间：{start}
                                        <UpdateDatePopup onSuccess={load} origin={id} title={'生效时间'} current={start} url={`/api/${url}-start-history`} />
                                    </Space>
                                </Grid.Item>
                            </Grid>
                            <Grid columns={1} gap={8} style={{ marginTop: "8px" }}>
                                <Grid.Item span={1}>
                                    <Space wrap>
                                        创建人：{creator.name}
                                    </Space>
                                </Grid.Item>
                            </Grid>

                            <Grid columns={1} gap={8} style={{ marginTop: "8px" }}>
                                <Grid.Item >
                                    <Space wrap>说明：{remark}
                                        <UpdateNamePopup onSuccess={load} origin={id} title='说明' current={remark} url={`/api/${url}-remark-history`} />
                                    </Space>
                                </Grid.Item>
                            </Grid>
                            <Grid columns={1} gap={8} style={{ marginTop: "8px" }}>
                                <Grid.Item >
                                    {sp && sp(living)}
                                </Grid.Item>
                            </Grid>
                            <Grid columns={1} gap={8} style={{ marginTop: "8px" }}>
                                <Grid.Item>
                                    <Space wrap>
                                        标准描述：{type.standard.name}
                                    </Space>
                                </Grid.Item>
                            </Grid>
                            <Grid columns={1} gap={8} style={{ marginTop: "8px" }}>
                                <Grid.Item >
                                    <Space wrap>创建时间:{dayjs(createdAt).format(DATE_TIME_FORMAT)}</Space>
                                </Grid.Item>
                            </Grid>
                        </>}
                    >
                        <h6>{leader.name} <Divider direction={'vertical'} /> {type.label}
                            <Divider direction={'vertical'} />
                            <DeleteButton url={`/api/${url}/delete/${id}`} onSuccess={load} />
                        </h6>

                    </List.Item>
                })}
            </List>}</DemoBlock>
}

export default StaffLivings;

export const SimpleStaffLivings: FC<{ url: string, origin: number, includeDescendants: boolean, addContent: (x: number) => any }> = ({ url, origin, includeDescendants, addContent }) => {

    const [loadFails, setLoadFails] = useState<string[]>([]);
    const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
    const [loadingTimes, setLoadingTimes] = useState<number>(3);
    const [livings, setLivings] = useState<StaffLiving[]>([]);

    function load() {
        let times = 1;
        const mznmf = `/api/${url}/${includeDescendants ? 'get-livings-by-origin-and-descendants' : 'get-livings-by-origin'}/${origin}`;
        let mznmfResponse: Promise<Response> = fetch(`${urlPrefix}${mznmf}`, getRequestInit())
        mznmfResponse.then(async (rsp: Response) => {
            if (rsp.ok) {
                await rsp.json().then(async ({ data, code, msg }: DetailResult<StaffLiving[]>) => {
                    if (code === 0) {
                        setLoadOK(msg);
                        setLivings(data!);
                    } else {
                        setLoadFails([...loadFails, msg]);
                    }
                }).catch(reason => {
                    setLoadFails([...loadFails, reason]);
                }).finally(() => {
                    console.log(`${mznmf} inner finally!`)
                })
            }
        }).catch((reason: any) => {
            console.error(reason);
            setLoadFails([...loadFails, `请求${mznmf}时发生错误：${reason}`])
        }).finally(() => {
            console.log(`${mznmf} outter finally!`)
            setLoadingTimes(--times);
        })
    }

    useEffect(load, [origin, url]);

    if (loadingTimes > 0) {
        return <div style={{ color: '#00b578' }}>
            <DotLoading color='currentColor' />
            <span>正在载入{loadingTimes}次...</span>
        </div>;
    }
    if (livings.length <= 0) {
        return addContent(origin);
    }

    return <Space>
        {livings.map(({ leader, type, start, createdAt, remark, creator, id }) => {
            return <React.Fragment key={id}>{leader.name}{type.label.indexOf('参与') >= 0 ? '' : `(${type.label})`}</React.Fragment>
        })}
        {addContent(origin)}
    </Space>
}

